package io.dcloud.h527baaa6.activity;

import android.Manifest;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.os.Handler;
import android.support.annotation.NonNull;
import android.text.TextUtils;
import android.util.Log;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.webkit.GeolocationPermissions;
import android.webkit.JavascriptInterface;
import android.webkit.WebChromeClient;
import android.webkit.WebView;
import android.webkit.WebViewClient;
import android.widget.FrameLayout;
import android.widget.ProgressBar;
import android.widget.Toast;

import com.tbruyelle.rxpermissions2.RxPermissions;

import butterknife.BindView;
import io.dcloud.h527baaa6.R;
import io.dcloud.h527baaa6.ar.VuforiaSamples.app.ImageTargets.ImageTargets;
import io.dcloud.h527baaa6.base.BaseActivity;
import io.dcloud.h527baaa6.utils.AlertDialogUtils;
import io.reactivex.functions.Consumer;


public class WebActivity extends BaseActivity {


    @BindView(R.id.web_container)
    public FrameLayout mWebContainer;
    public WebView mWebView;
    @BindView(R.id.progressBar1)
    ProgressBar mProgressBar1;
    private String title;

    /**
     * 启动activity
     *
     * @param mContext
     * @param url
     */
    public static void startActivity(Context mContext, String url) {

        Intent intent = new Intent(mContext, WebActivity.class);
        intent.putExtra("url", url);
        mContext.startActivity(intent);

    }

    /**
     * 获取布局Id
     */
    @Override
    protected int getLayout() {
        return R.layout.activity_web_layout;
    }

    /**
     * 获取标题title
     */
    @Override
    protected int getTitleText() {
        return 0;
    }

    /**
     * 初始化布局和数据
     */
    @Override
    protected void initViewAndData() {
        mLoadingView.setShowLoading(true);
        if (!TextUtils.isEmpty(title))
            mToobarTitleView.setTitleText(title);
        String url = getIntent().getStringExtra("url");
        initWebView(url);

     /*   UMShareAPI.get(this).getPlatformInfo(this, SHARE_MEDIA.WEIXIN, new UMAuthListener() {
            @Override
            public void onStart(SHARE_MEDIA share_media) {
                Log.i("qqq","onStart");
            }

            @Override
            public void onComplete(SHARE_MEDIA share_media, int i, Map<String, String> map) {
                Log.i("qqq","onComplete");
                for (Map.Entry<String, String> entry :map.entrySet()){
                    Log.i("sss",entry.getKey()+"值："+entry.getValue());
                }

            }

            @Override
            public void onError(SHARE_MEDIA share_media, int i, Throwable throwable) {
                Log.i("qqq","onError");
            }

            @Override
            public void onCancel(SHARE_MEDIA share_media, int i) {
                Log.i("qqq","onCancel");
            }
        });*/
    }


    /**
     * Js调用Android 原生方法
     */
    private class JS {
        @JavascriptInterface
        public void showInfoFromJs(String string) {
            Log.i("sss","调用Android方法"+string);
            RxPermissions rxPermission = new RxPermissions(mContext);
            rxPermission.request(Manifest.permission.CAMERA)
                    .subscribe(new Consumer<Boolean>() {
                        @Override
                        public void accept(@NonNull Boolean aBoolean) throws Exception {
                            if (aBoolean) {
                                // 用户已经同意该权限
                                Intent intent = new Intent(WebActivity.this, ImageTargets.class);/*
                            intent.putExtra("ABOUT_TEXT_TITLE", "AR识别");
                            intent.putExtra("ACTIVITY_TO_LAUNCH",
                                    "ar.VuforiaSamples.app.ImageTargets.ImageTargets");
                            intent.putExtra("ABOUT_TEXT", "ImageTargets/IT_about.html");*/
                                startActivity(intent);
                            } else {
                                // 用户拒绝了该权限，并且选中『不再询问』
                                AlertDialogUtils.showDialog(mContext, "请在设置中心打开相机权限", new AlertDialogUtils.OnPositiveListener() {
                                    @Override
                                    public void onPostive() {
                                        try {
                                            Intent localIntent = new Intent();
                                            localIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                                            localIntent.setAction("android.settings.APPLICATION_DETAILS_SETTINGS");
                                            localIntent.setData(Uri.fromParts("package", mContext.getPackageName(), null));
                                            mContext.startActivity(localIntent);
                                        } catch (Exception e) {

                                        }
                                        finish();
                                    }

                                    @Override
                                    public void onNegative() {
                                        finish();
                                    }
                                });
                            }
                        }
                    });
        }
    }
    /**
     * 初始化web界面
     */
    private void initWebView(String url) {
        mWebView = new WebView(this);
        mWebView.setWebViewClient(new MyWebViewClient());
        mWebView.setWebChromeClient(new MyWebChromrClient());
        //启用数据库
        mWebView.getSettings().setDatabaseEnabled(true);
        //设置定位的数据库路径
        String dir = this.getApplicationContext().getDir("database", Context.MODE_PRIVATE).getPath();
        mWebView.getSettings().setGeolocationDatabasePath(dir);
        //启用地理定位
        mWebView.getSettings().setGeolocationEnabled(true);
/*        //开启DomStorage缓存
        mWebView.getSettings().setDomStorageEnabled(true);
        mWebView.getSettings().setCacheMode(WebSettings.LOAD_CACHE_ELSE_NETWORK);// 优先使用缓存
        mWebView.getSettings().setAppCacheMaxSize(20 * 1024 * 1024);// 缓存最多可以有10M
        mWebView.getSettings().setAppCacheEnabled(true);
        mWebView.getSettings().setAllowFileAccess(true);// 可以读取文件缓存(manifest生效)*/
        mWebView.getSettings().setBuiltInZoomControls(false);
        mWebView.getSettings().setLoadWithOverviewMode(true);
        mWebView.getSettings().setUseWideViewPort(true);
        mWebView.getSettings().setJavaScriptEnabled(true);
        mWebView.getSettings().setTextZoom(100);
        mWebView.setLayoutParams(new FrameLayout
                .LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
        mWebContainer.addView(mWebView, 0);
        mWebView.loadUrl(url);
        mWebView.addJavascriptInterface(new JS(),"AndroidWebView");
    }
    public class MyWebChromrClient extends WebChromeClient {
        @Override
        public void onProgressChanged(WebView view, int newProgress) {
            if (newProgress == 100) {
                mProgressBar1.setVisibility(View.GONE);//加载完网页进度条消失
            } else {
                mProgressBar1.setVisibility(View.VISIBLE);//开始加载网页时显示进度条
                mProgressBar1.setProgress(newProgress);//设置进度值
            }
        }
        @Override
        public void onGeolocationPermissionsShowPrompt(String origin, GeolocationPermissions.Callback callback) {
            Log.i("qqq",origin);
            callback.invoke(origin,true,false);
            super.onGeolocationPermissionsShowPrompt(origin, callback);
        }
    }
    public class MyWebViewClient extends WebViewClient {

        @Override
        public void onLoadResource(WebView view, String url) {
            super.onLoadResource(view, url);
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);
            int w = View.MeasureSpec.makeMeasureSpec(0,
                    View.MeasureSpec.UNSPECIFIED);
            int h = View.MeasureSpec.makeMeasureSpec(0,
                    View.MeasureSpec.UNSPECIFIED);
            // 重新测量
            mWebView.measure(w, h);
            new Handler().postDelayed(new Runnable() {
                @Override
                public void run() {
                    mLoadingView.setShowLoading(false);
                }
            }, 200);

        }

    }


    @Override
    protected void onDestroy() {
        mWebView.removeAllViews();
        mWebView.destroy();
        mWebView = null;
        mWebContainer.removeAllViews();
        super.onDestroy();
    }


    @Override
    public boolean onTouchEvent(MotionEvent event) {
        Toast.makeText(mContext, "点击了", Toast.LENGTH_LONG).show();
        return true;
    }
}
